<?php
/**
* 任务计划 - 分钟执行的任务
* 执行频率1-2分钟
*
*
*
* @copyright  Copyright (c) 中国追溯
* @since      File available since Release v1.1
*/
defined('InShopNC') or exit('Access Invalid!');

class realtimeControl extends BaseCronControl {
    public function indexOp() {
        $this->_realtime_msg();
        $this->_realtime_promotion();
        $this->robotOp();
    }

     /**
     * 向第三方发消息通知
     */
    private function _realtime_msg() {
        $sms = new Sms();
        $model_realtime_msg = Model('realtime_msg');
        $list = $model_realtime_msg->getMsgList(array(), '', 60, 'log_id asc');//默认每次处理60个
        if(!empty($list) && is_array($list)) {
            foreach($list as $k => $v) {
                $msg_type = $v['msg_type'];//类型:1邮件,2短信,3微信
                $result = true;
                switch ($msg_type) {
                    case '1':
                        try {
                            $_v = C('email_pass');
                            if (!empty($_v)) $model_realtime_msg->send($v['to_id'],$v['subject'],$v['log_msg']);
                            $result = true;
                        } catch (Exception $ex) {
                            $result = false;
                        }
                        break;
                    case '2':
                        $_v = C('sms.serialNumber');
                        if (!empty($_v)) $result = $sms->send($v['to_id'],$v['log_msg']);
                        break;
                    case '3':
                        $logic_wx_api = Logic('wx_api');
                        $access_token = $logic_wx_api->getAccessToken();
                        if (!empty($access_token)) $result = $logic_wx_api->sendTemplate($access_token,$v);
                        break;
                    case '4':
                        $logic_applet_notice = Logic('applet_notice');
                        $access_token = $logic_applet_notice->getAccessToken();
                        if (!empty($access_token)) $result = $logic_applet_notice->sendTemplate($access_token,$v);
                        $result = true;
                        break;
                }
                if($result) $model_realtime_msg->delMsg($v);
            }
        }
    }

    /**
     * 价格促销时间(限时折扣、秒杀、闪购)
     */
    private function _realtime_promotion() {
        $model_p_time = Model('p_time');
        $model_goods = Model('goods');
        $condition = array();
        $condition['end_time'] = array('elt',TIMESTAMP);
        $model_p_time->del($condition);//过期处理
        Model('p_xianshi')->editExpireXianshi();
        Model('p_spike')->editExpireSpike();
        Model('p_flash')->editExpireFlash();
        
        $condition = array();
        $condition['is_update'] = 0;
        $condition['start_time'] = array('elt',TIMESTAMP);
        $list = $model_p_time->table('p_time')->where($condition)->select();
        if(!empty($list) && is_array($list)) {//更新处理
            foreach($list as $k => $v) {
                $model_goods->editGoodsPromotionPrice(array('goods_id' => $v['goods_id']),$v);
                $model_p_time->edit(array('log_id' => $v['log_id']),array('is_update' => 1));
            }
        }
    }

    
    /**
     * 机器人错误日志
     * */
    private function robot_log($msg){
    	$this->log($msg);
    	exit();
    }
   	
   	/**
   	 * 获取所有还没拼团成功的团长
   	 * */
   	private function get_pintuan_first($config){
   		$where=array(
			"pay_time"   => array("gt",1),
			"end_time"   => array('gt',TIMESTAMP-$config[0]['robot_time']),
			"lock_state" => 1,
			"buyer_type" => 0
		);
		$cp=$list = Model("order_pintuan")->getList($where,'','','*',false);
   		foreach($cp as $k => $v){
   			//当前时间 小于 支付时间+设置时间
   			if(TIMESTAMP>($v['pay_time']+$config[0]['robot_time'])){
   				unset($list[$k]);
   			}
   		}
   		return $list;
   	}
   	
   	/**
   	 * 获取该拼团的所有队员
   	 * */
   	private function get_pintuan_parent($id){
   		$where=array(
			"pay_time"   => array("gt",1),
			"end_time"   => array('gt',TIMESTAMP),
			"lock_state" => 1,
			"buyer_type" => $id
		); 
		return Model("order_pintuan")->getList($where,'','','*',false);
   	}
   	
   	/**
   	 * 判断拼团人数达标,达标更新订单状态
   	 * */
   	private function check_pintuan($order){
   		$parents=$this->get_pintuan_parent($order['log_id']);
   		if($order['min_num']==count($parents)+1){
   			//更改该拼团所有订单状态
   			array_push($parents,$order);
   			foreach($parents as $v){
   				$where=array("log_id"=>$v['log_id']);
   				Model("order_pintuan")->save($where,array("lock_state"=>0));
   			}
   		}
   	}
   	
   	/**
   	 * 添加一条机器人拼团订单
   	 * */
   	private function add_pintuan_robot($order){
   		$time=time();
   		$order_sn='1000'.time().rand(0,9).rand(0,9).rand(0,9);
   		$insert=array(
   			"order_sn"   => $order_sn,
   			"pay_sn"     => 100 ,
   			"store_id"   => $order['store_id'] ,
   			"store_name" => '无',
   			"buyer_id"   => 1,
   			"buyer_name" => 'rb',
   			"buyer_email"=> 'zhuisushangcheng.com',
   			"buyer_phone"=> '13888888888',
   			"add_time"   => $time ,
   			"payment_code"=> 'online' ,
   			"finnshed_time"=> 0 ,
   			"payment_time" => $time ,
   			"goods_amount" => $order,
   			"order_amount" => '0.01',
   			"rcb_amount"   => '0.01',
   			"pd_amount"    => 0 ,
   			"shipping_fee" => 0,
   			"evaluation_state" => 0,
   			"evaluation_again_state" => 0,
   			"order_state" => 20 ,
   			"refund_state" => 0,
   			"lock_state" => 0,
   			"delete_state" => 0,
   			"refund_amount" => 0,
   			"delay_time" => 0,
   			"order_from" => 999,
   			"shipping_code" => '',
   			"order_type" => 4,//拼团为4，砍价为200
   			"api_pay_time" => $time,
   			"chain_id" => 0,
   			"chain_code" => 0,
   			"rpt_amount" => 0,
   			"trade_no" => '',
   			"is_dis" => 0,
   			"chain_sender_state" => 0
   		);
   		Model("order")->add($insert);
   		$where=array("order_sn"=>$order_sn);
   		$order_id=Model("order")->getOrderId($where);
   		$insert=array(
   			"order_id" => $order_id['order_id'],
   			"order_sn" => $order_sn,
   			"buyer_type" => $order['log_id'],
   			"buyer_id" => 1,
   			"buyer_name" => 'rb',
   			"goods_id" => $order['goods_id'],
   			"goods_commonid" => $order['goods_commonid'],
   			"min_num" => $order['min_num'],
   			"add_time" => $time,
   			"pay_time" => $time,
   			"end_time" => $order['end_time'],
   			"cancel_time" => $time,
   			"store_id" => $order['store_id'],
   			"lock_state" => 1
   		);
   		Model("order_pintuan")->add($insert);
   		$insert=array(
   			"order_id" => $order_id['order_id'],
   			"store_id" => $order['store_id'],
   			"shipping_time" => 0,
   			"shipping_express_id" => 0,
   			"evaluation_time" => $order['store_id'],
   			"order_message" => "自动拼团订单",
   			"order_pointscount" => 0,
   			"voucher_price" => '',
   			"voucher_code" => '',
   			"deliver_explain" => '',
   			"daddress_id" => 0,
   			"reciver_name" => '自动拼团',
   			"reciver_info" => 'a:6:{s:5:"phone";s:11:"13888888888";s:9:"mob_phone";s:11:"13888888888";s:9:"tel_phone";s:0:"";s:7:"address";s:75:"河北 秦皇岛市 山海关区 地方";s:4:"area";s:32:"河北 秦皇岛市 山海关区";s:6:"street";s:42:"地方";}',
   			"reciver_province_id" => 19,
   			"reciver_city_id" => 289,
   			"invoice_info" => 'a:0:{}',
   			"promotion_info" => '',
   			"dlyo_pickup_code" => '',
   			"promotion_total" => 0,
   			"discount" => 0,
   			"reciver_date_msg" => '节假日送货',
   		);
   		Model("order_common")->add($insert);
   	}
   	
   	/**
   	 * 自动拼团实现方法
   	 * */
    private function pintuan_robot($config){
    	if($config[0]['robot'] == 1){
    		//获取团长
    		$orderList=$this->get_pintuan_first($config);
			foreach($orderList as $k => $v){
				//获取团员
				$parents=$this->get_pintuan_parent($v['log_id']);
				$total=count($parents)+1;
				if($total < $v['min_num']){
					for($i=0;$i<$v['min_num']-$total;$i++){
						$this->add_pintuan_robot($v);
						$this->check_pintuan($v);
					}
				}
			}
    	}else{
    		$this->robot_log('拼团机器人已关闭');
    	}
    }
    
  	/**
     * 判断砍价是否重复
     * @author Harris
     * */
    private function isKanjiaOp($order,$buyer){
    	if(!in_array($buyer['member_id'],$order['kanjia_price']['members'])){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 添加一条机器人砍价
     * @author Harris
     * @param  整个订单数组
     * */
    private function addRobot($order){
    	$robot=Model("member")->getRobotList();
		array_push($order['kanjia_price']['members'],$robot['member_id']);
    	$user=array(
			"name"=>$robot['member_name'],
			"icon"=>getMemberAvatarHttps($robot['member_avatar']),
			"time"=>date("Y-m-d H:i:s")
		);
    	array_push($order['kanjia_price']['people'],$user);
		return $order;
    }
    
    /**
     * 自动砍单
     * */
    private function kanjia_robot($config){
    	if($config[1]['robot'] == 1){
    		//获取砍价尚未成功订单
    		$where=array(
    			"status"=>0,
    			"pay_time"   => array("gt",1),
				"end_time"   => array('gt',TIMESTAMP),
    		);
    		$orderList=Model()->table("order_kanjia")->where($where)->select();
			foreach($orderList as $k => $v){
				//支付时间+设置时间  大于 当前时间
				if(($v['pay_time']+$config[1]['robot_time'])>TIMESTAMP){					
					$this->add_kanjia_robot($v);	
				}
			}
    	}else{
    		$this->robot_log('拼团机器人已关闭');
    	}
    }
    
    /**
     * 添加机器人砍单记录
     * */
    private function add_kanjia_robot($order){
    	$order['kanjia_price']=json_decode($order['kanjia_price'],true);
    	while($order['kanjia_price']['now']<$order['kanjia_price']['total']){
			$order['kanjia_price']['now']<$order['kanjia_price']['total']?$order=$this->addRobot($order):'';
			if($order['kanjia_price']['now']<$order['kanjia_price']['total']){
				$order['kanjia_price']['now']+=1;
			}
			$update=array("kanjia_price"=>json_encode($order['kanjia_price']));
			//判断是否砍价完成
			$order['kanjia_price']['now']==$order['kanjia_price']['total']?$update['status']=1:'';
			$condition=array("order_sn"=>$order['order_sn']);
			Model("p_kanjia")->editKanjiaOrder($update,$condition);
			$order=Model("order_kanjia")->getKanjiaOrder($condition);
    	}
    }
    
    
    /**
     * 定时任务 自动拼团/砍价
     * */
    public function robotOp(){
    	$config=Model("robot_config")->getConfig();
    	$config?'':$this->robot_log('读取机器配置失败');
    	$this->pintuan_robot($config);
    	$this->kanjia_robot($config);
    	
    	$res=Model()->table("order_kanjia")->where("log_id = '119'")->find();
    	$res['kanjia_price']=json_decode($res['kanjia_price'],true);
    }
    
    
}
